import axios, {
  AxiosError,
  type AxiosRequestConfig,
  type AxiosResponse,
  type InternalAxiosRequestConfig,
} from 'axios'
import { useUserStore } from '@/stores/user'

export const baseURL = 'http://geek.itheima.net/'

const request = axios.create({
  baseURL,
  timeout: 10000,
})

request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStore()

    if (userStore.token) {
      config.headers['Authorization'] = `Bearer ${userStore.token}`
    }

    return config
  },
  (err: AxiosError) => {
    return Promise.reject(err)
  },
)

request.interceptors.response.use(
  (res: AxiosResponse) => {
    if (res.data.message == 'OK') {
      return res.data.data
    }

    return Promise.reject(res.data.message)
  },
  (err: AxiosError) => {
    return Promise.reject(err)
  },
)

class Http {
  get<T>(url: string, config?: AxiosRequestConfig) {
    return request.get<null, T>(url, config)
  }
  post<T>(url: string, data?: object) {
    return request.post<null, T>(url, data)
  }
  put<T>(url: string, data?: object) {
    return request.put<null, T>(url, data)
  }
  delete<T>(url: string, params?: object) {
    return request.delete<null, T>(url, { params })
  }
}

export const http = new Http()
